package cn.itcast.oa.util;

import java.util.ArrayList;
import java.util.List;

import com.opensymphony.xwork2.ActionContext;

import cn.itcast.oa.base.BaseDAO;
import cn.itcast.oa.model.PageBean;

public class HqlHelper {
	private String fromClause; // From子句，必须
	private String whereClause = ""; // Where子句，可选
	private String orderByClause = ""; // OrderBy子句，可选
	
	private ArrayList<Object> parameters=new ArrayList<Object>();
	
	/**
	 * 生成From子句，默认的别名为'o'
	 * 
	 * @param clazz
	 */
	public HqlHelper(Class clazz) {
		this.fromClause = "FROM " + clazz.getSimpleName() + " o";
	}
	
	/**
	 * 生成From子句，使用指定的别。'
	 * 
	 * @param clazz
	 * @param alias
	 *            别名
	 */
	public HqlHelper(Class clazz, String alias) {
		this.fromClause = "FROM " + clazz.getSimpleName() + " " + alias;
	}
	
	public HqlHelper addCondition(String condition,Object... params){
		
		if(whereClause.length()==0){
			whereClause=" WHERE "+condition;
		}else{
			whereClause+=" AND "+condition;
		}
		
		/**
		 * 保存参数
		 */
		if(params.length>0&&params!=null){
			for(Object object:params){
				parameters.add(object);
			}
		}
		return this;
	}
	
	/**
	 * 如果第1个参数为true，则拼接Where子句
	 * 
	 * @param append
	 * @param condition
	 * @param params
	 */
	public HqlHelper addCondition(boolean append, String condition, Object... params) {
		if (append) {
			addCondition(condition, params);
		}
		return this;
	}
	
	/**
	 * 拼接OrderBy子句
	 * 
	 * @param propertyName
	 *            属性名
	 * @param isAsc
	 *            true表示升序，false表示降序
	 */
	public HqlHelper addOrder(String propertyName, boolean isAsc) {
		if (orderByClause.length() == 0) {
			orderByClause = " ORDER BY " + propertyName + (isAsc ? " ASC" : " DESC");
		} else {
			orderByClause += ", " + propertyName + (isAsc ? " ASC" : " DESC");
		}
		return this;
	}
	
	/**
	 * 如果第1个参数为true，则拼接OrderBy子句
	 * 
	 * @param append
	 * @param propertyName
	 *            属性名
	 * @param isAsc
	 *            true表示升序，false表示降序
	 */
	public HqlHelper addOrder(boolean append, String propertyName, boolean isAsc) {
		if (append) {
			addOrder(propertyName, isAsc);
		}
		return this;
	}
	
	/**
	 * 获取生成的查询数据列表的HQL语句
	 * 
	 * @return
	 */
	public String getQueryListHql() {
		return fromClause + whereClause + orderByClause;
	}
	
	public String getQueryCountHql() {
		return "SELECT COUNT(*) " + fromClause + whereClause;
	}

	/**
	 * 获取参数列表，与HQL过滤条件中的'?'一一对应
	 * 
	 * @return
	 */
	public List<Object> getParameters() {
		return parameters;
	}
   
	public HqlHelper buildPageBeanForStruts2(int pageNum, BaseDAO<?> service) {
		System.out.println("===> HqlHelper.buildPageBeanForStruts2()");
		System.out.println(this);
		PageBean pageBean = service.getPageBean(pageNum, this);

		ActionContext.getContext().getValueStack().push(pageBean);
		return this;
	}
}
